<?php
namespace Foxframe;

class Filter
{
	public $session = 'filter';
	public $application;
	public $controller;
	public $filter;
	public $filterSession;
	public $maxResults;
	public $actualPage;

	public function __construct($preFiltro = array())
	{
		$this->application	= Uri::getInstance()->get('application');
		$this->controller	= Uri::getInstance()->get('method');

		if (!isset($_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['maxResults']))
			$this->setMaxResults();

		if (!isset($_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['actualPage']))
			$this->setActualPage();

		if (count($preFiltro) || !isset($_SESSION[$this->session][$this->application][$this->controller]['filter']))
			$this->setFilter($preFiltro);
	}

	public function getFilter()
	{
		return $_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['filter'];
	}

	public function getQueryFilter()
	{
		$filtro	= array();
		foreach ($_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['filter'] as $key => $value)
		{
			if (is_null($value))
				continue;
			$filtro[$key] = $value;

		}
		return $filtro;
	}

	public function setFilter($preFiltro = array())
	{
		if (is_array($preFiltro))
		{
			$this->filter	= $preFiltro;
			$_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['filter'] = $preFiltro;
		}
	}

	public function get($atributo)
	{
		if (isset($_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['filter'][$atributo]))
			return $_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['filter'][$atributo];
		else
			return false;
	}

	public function setMaxResults($value = 15)
	{
		$_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['maxResults']	= (int) $value;
		$this->maxResults = (int) $value;
	}

	public function getMaxResults()
	{
		return $_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['maxResults'];
	}

	public function setActualPage($value = 1)
	{
		$_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['actualPage']	= (int) $value;
		$this->actualPage = (int) $value;
	}

	public function getActualPage()
	{
		return $_SESSION[SESSION_LOGIN][$this->session][$this->application][$this->controller]['actualPage'];
	}

	public function getFirstResult()
	{
		if ($this->getActualPage() == 1)
			return 0;
		else
			return	($this->getMaxResults() * $this->getActualPage()) - $this->getMaxResults();
	}
}